package com.hbnu.thread;

public class Box {

    private int product = 0;
    public synchronized void addProduct() {
        if (product < 20) {
            product++;
            System.out.println("生产了" + product + "号牛奶");
            notifyAll();
        }
        else {
            try {
                wait();     //此句只能在同步代码块中
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }



    }

    public synchronized void getProduct() {
        if (product <= 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            notifyAll();        //没有产品时唤醒生产线程
        }
        else {
            product--;
            System.out.println("消费了" + product + "号牛奶");
            notifyAll();
        }
    }
}


